﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;

namespace WPFStudy.Extensions
{
    /// <summary>
    /// XAML标记扩展提供基类(MarkupExtension)需要用到ProvideValue方法时，参数 IServiceProvider 的实现类
    /// 使用方法示例
    /// <code>
    /// private void TextBlock_Loaded(object sender, RoutedEventArgs e)
    /// {
    ///     if(sender is TextBlock tb)
    ///     {
    ///         //绑定选中字段
    ///         Binding objBinding = new Binding();
    ///         objBinding.Path = new PropertyPath(Path的变量值);
    ///         objBinding.Source = tb.DataContext;
    ///         objBinding.Mode = BindingMode.TwoWay;
    ///         objBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    ///         objBinding.NotifyOnTargetUpdated = true;
    ///         objBinding.NotifyOnSourceUpdated = true;
    ///         LBinding lBinding = new LBinding(objBinding);
    ///         tb.SetBinding(TextBlock.TextProperty, objBinding);
    ///         lBinding.ProvideValue(new MarkupExtensionTarget(tb, TextBlock.TextProperty));
    ///     }
    /// }
    /// </code>
    /// </summary>
    public class MarkupExtensionTarget : IServiceProvider, IProvideValueTarget
    {
        private readonly DependencyObject _targetObject;
        private readonly DependencyProperty _targetProperty;

        public MarkupExtensionTarget(DependencyObject targetObject, DependencyProperty targetProperty)
        {
            _targetObject = targetObject;
            _targetProperty = targetProperty;
        }

        public object GetService(Type serviceType)
        {
            if (serviceType == typeof(IProvideValueTarget))
                return this;
            return null;
        }

        object IProvideValueTarget.TargetObject { get { return _targetObject; } }
        object IProvideValueTarget.TargetProperty { get { return _targetProperty; } }
    }
}
